package net.huashitong.supervision.AppNew.appCtrl;

import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.AppNew.DTO.UserDTO;
import net.huashitong.supervision.AppNew.appService.AppTaskService;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.TaskBackNewFilter;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.service.*;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/app/task")
public class AppTaskCtrl extends JsonBaseController {

    @Override
    protected String getView(String s) {
        return null;
    }
    @Autowired
    private RedisService redisService;
    @Autowired
    private TaskNewListService taskNewListService;
    @Autowired
    private TaskLogNewService taskLogNewService;
    @Autowired
    private TaskUnitService taskUnitService;
    @Autowired
    private TaskBackNewService taskBackNewService;
    @Autowired
    private TaskMainService taskMainService;
    @Autowired
    private AppTaskService appTaskService;

    @Autowired
    private
    TaskCategoryService categoryService;
    @Autowired
    private SpecialTaskService specialTaskService;



    /**
     * 获取代签收 ，已反馈的总数
     */
    @ResponseBody
    @RequestMapping(value = "/taskcount",method = RequestMethod.GET)
    public Message getTaskCount(String loginerId,HttpServletResponse response)
    {

      //  String loginerId = unitFilter.getLoginerId();
        TaskUnitFilter unitFilter= new TaskUnitFilter();
        Paging paging = new Paging();
        paging.setPageSize(10);
        paging.setCurrentPage(1);
        unitFilter.setPaging(paging);
        String jsonUser = redisService.get("applogin:dc:" + loginerId);
//        JSONObject.toJavaObject(jsonUser, UserDTO.class);
        UserDTO userDTO = JSONObject.parseObject(jsonUser, UserDTO.class);
        unitFilter.setUserDTO(userDTO);
        //代签收
        unitFilter.setImp(0);
        unitFilter.setType(0+"");

        TaskUnitFilter backFilter= new TaskUnitFilter();
        Paging page2 = new Paging();
        page2.setPageSize(10);
        page2.setCurrentPage(1);
        backFilter.setPaging(page2);
        backFilter.setUserDTO(userDTO);

        //未反馈
        backFilter.setImp(0);

        backFilter.setType(1+"");

        if(StringUtils.isBlank(loginerId))
        {
            return coverMessage("500" ,"您已离线，重新登录");

        }
        String roleId = userDTO.getRoleId();
        String deptId = userDTO.getDeptId();
        if("04".equals(roleId)){
            unitFilter.setUserId(loginerId);
            backFilter.setUserId(loginerId);

        }else if("02".equals(roleId)) {
            unitFilter.setUserId(loginerId);
            unitFilter.setCreateUser(loginerId);
            unitFilter.setDeptId(deptId);

            backFilter.setUserId(loginerId);
            backFilter.setCreateUser(loginerId);
            backFilter.setDeptId(deptId);


        }else {
            unitFilter.setDeptId(null);
            unitFilter.setUserId(loginerId);

            backFilter.setDeptId(null);
            backFilter.setUserId(loginerId);


        }
        List<TaskUnit> unsignList = taskNewListService.getNormalTaskList(unitFilter);

        List<TaskUnit> backlist = taskNewListService.getNormalTaskList(backFilter);


        int unsignNum = 0;
        unsignNum= unitFilter.getPaging().getRecords();
        int unbackNum = 0;
        unbackNum=backFilter.getPaging().getRecords();
        HashMap<String,String> map = new HashMap<>();
        map.put("unsign",unsignNum+"");
        map.put("unback",unbackNum+"");
        return  coverMessage("200","统计数",map);
    }


    /**
     * 获取普通任务
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tasklists",method = RequestMethod.POST)
    public Message getNorTask(@RequestBody  TaskUnitFilter unitFilter,  HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");

        String loginerId = unitFilter.getLoginerId();
//        Paging paging = new Paging();
//        paging.setPageSize(10);
//        paging.setCurrentPage(1);
//        unitFilter.setPaging(paging);
        if(ObjectUtils.isBlank(loginerId))
        {
            return coverMessage("500");
        }

        //获取当前用户登录信息
        UserDTO userDTO = getUserInfo(loginerId);
        if(ObjectUtils.isBlank(userDTO))
        {
            return coverMessage("500","您已经掉线 请重新登陆 ");
        }
        unitFilter.setUserDTO(userDTO);

        String loginId = userDTO.getUserId();
        String roleId = userDTO.getRoleId();
        String deptId = userDTO.getDeptId();

        if("04".equals(roleId)){
            unitFilter.setUserId(loginId);

        }else if("02".equals(roleId)) {
            unitFilter.setUserId(loginId);
            unitFilter.setCreateUser(loginId);
            unitFilter.setDeptId(deptId);
        }else {
            unitFilter.setDeptId(null);
            unitFilter.setUserId(loginId);
        }

        List<TaskUnit> normalTaskList = taskNewListService.getNormalTaskList(unitFilter);
        for (TaskUnit taskUnit : normalTaskList) {
            TaskMain taskMain = taskMainService.getById(taskUnit.getTaskMainId());
            if(ObjectUtils.isBlank(taskMain))
            {
                continue;
            }
            String categoryId = taskMain.getCategoryId();
            String  cateName ="";
            if(StringUtils.isNotBlank(categoryId))
            {

                 cateName = changeCateVale(categoryId);
            }
            taskUnit.setCategoryName(cateName);
            String taskSubName = taskUnit.getTaskSubName();
            String taskMainName = taskUnit.getTaskMainName();
            taskUnit.setTaskSubName(StringUtils.isNotBlank(taskSubName)?StringEscapeUtils.unescapeHtml(taskSubName):"");
            taskUnit.setTaskMainName(StringUtils.isNotBlank(taskMainName)?StringEscapeUtils.unescapeHtml(taskMainName):"");

        }

        return  coverMessage("200","任务获取成功",normalTaskList);
    }

    private String  changeCateVale(String categoryId){
        String  name ="" ;
        if(ObjectUtils.isBlank(categoryId))
        {
            return "其他";
        }
        if("gongjianTask".equals(categoryId)){
//            taskUnit.setCategoryName("攻坚任务");
            name="攻坚任务";
            return  name;
        }
        TaskCategory cate = categoryService.getById(categoryId);
        if(ObjectUtils.isBlank(cate))
        {
            name="其他";
            return name;
        }

        name=cate.getCategory();
        return name;
    }


    /**
     * 更改任务状态
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changetype",method = RequestMethod.POST)
    public Message changeTaskType(@RequestBody TaskUnitFilter filter){
        String sysId = filter.getSysId();
        if(StringUtils.isBlank(sysId)){
            return coverMessage("500","单位任务Id不能为空");
        }
        String loginId = filter.getLoginerId();
        UserDTO userInfo = getUserInfo(loginId);

        int i = appTaskService.updateTaskType(sysId, "1", userInfo);
        if(0==-1)
        {
            coverMessage("500","状态更新失败");
        }
        return coverMessage("200","状态成功");
    }

    /**
     * 获取用户信息
     * @param loginId
     * @return
     */
    private UserDTO getUserInfo(String loginId){
        String jsonUser = redisService.get("applogin:dc:" + loginId);
        UserDTO userDTO = JSONObject.parseObject(jsonUser, UserDTO.class);
        return userDTO;
    }

    /**
     * 查看反馈记录历史记录
     */
    @ResponseBody
    @RequestMapping(value = "/taskrecord",method = RequestMethod.GET)
    public Message getUnitBackInfo(String taskUnitId,String loginerId)
        {

            UserDTO userInfo = getUserInfo(loginerId);
            String roleId = userInfo.getRoleId();
            List<TaskBackNew> ownRecords= new ArrayList<>();
            if("04".equals(roleId)){
                ownRecords = taskBackNewService.getByTaskUnitIdAndSenderId(taskUnitId, loginerId);

            }else {

                ownRecords = taskBackNewService.getByTaskUnitId(taskUnitId);
            }
            List<TaskBackNew> dataList = new ArrayList<>();

            dataList.addAll(ownRecords);
           /* ownRecords.forEach(taskBackNew -> {
                if(!"4".equals(taskBackNew.getDeptType())){
                    dataList.add(taskBackNew);
                }
            });*/

            return coverMessage("200","获取饭记录数据",dataList);
        }


    /**
     * 流程记录
     * @param taskUnitId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskrecordlog",method = RequestMethod.GET)
    public Message getNorTask(String taskUnitId,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");


        if(StringUtils.isBlank(taskUnitId)){

            return coverMessage("500","单位任务Id不可以为空");
        }
        List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);

        return coverMessage("200","流程记录反馈成功",logNewList);

    }

    /**
     * 批转
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveTaskUser", method = RequestMethod.POST)
    public Message saveTaskUser(@RequestBody TaskUnitFilter filter) {
        //userId  当前用户 sysId 单位任务id  taskUsers  批转人员id字符串，逗号拼接
        String loginId = filter.getLoginerId();
        filter.setUserId(loginId);
        if(StringUtils.isBlank(loginId))
        {
            coverMessage("500","你已经离线，请重新登陆");
        }
        String s = taskUnitService.saveTaskUser(filter);

        if ("200".equals(s)) {
//            批转成功 更新任务状态，改为未反馈。
//            appTaskService.changeTaskType(filter.getSysId(),"1");
            return coverMessage("200", "保存成功");
        } else {
            return coverMessage("500", "未添加经办人");
        }
    }

    /**
     * 承办单位反馈
     */
    @ResponseBody
    @RequestMapping(value = "/taskBackNew", method = RequestMethod.POST)
    public Message backTask(@RequestBody TaskBackNewFilter filter) {
        String loginerId = filter.getLoginerId();
        UserDTO userInfo = getUserInfo(loginerId);
        if(StringUtils.isBlank(loginerId))
        {
            coverMessage("200","登陆超时，请重新登录");
        }
        filter.setCreateId(loginerId);

        String taskUnitId = filter.getTaskUnitId();

        TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
        String backCode="";
        if(ObjectUtils.isNotBlank(taskUnit))
        {

             backCode = taskBackNewService.saveBack(filter);
        }else {

            SpecialTask specialTask = specialTaskService.getById(taskUnitId);
            String taskMainId = specialTask.getTaskMainId();
            filter.setTaskMainId(taskMainId);
            filter.setDeptId(userInfo.getDeptId());
            backCode = taskBackNewService.saveGongJianTaskBack(filter);
        }


        if ("200".equals(backCode)) {
            return coverMessage("200", "反馈成功");
        } else if ("500".equals(backCode)) {
            return coverMessage("500", "反馈失败");
        } else {
            return coverMessage("500", backCode);
        }
    }

    /**
     * 办结或者退回重办
     */

    @ResponseBody
    @RequestMapping(value = "/handletask")
    public Message handldTask(@RequestBody TaskBackNewFilter backNewFilter)
    {
        String loginerId = backNewFilter.getLoginerId();
        if(StringUtils.isBlank(loginerId))
        {
            coverMessage("500","您已经离线，请重新登录");
        }
        backNewFilter.setUserId(loginerId);

        String s = taskMainService.updateBackNew(backNewFilter);
        if("200".equals(s))
        {

            return coverMessage("200");
        }

        return coverMessage("500","参数错误，操作失败");


    }


    /**
     * 获取主任务
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/maintasklist",method = RequestMethod.POST)
    public Message getMainTask(@RequestBody TaskMainFilter filter)
    {
        String loginerId = filter.getLoginerId();
        if(StringUtils.isBlank(loginerId))
        {
            return coverMessage("500","登陆超时，重新登录");
        }

        UserDTO userDto = getUserInfo(loginerId);
        String roleId = userDto.getRoleId();
        /*
         * 01  县领导
         * 02  主要领导
         * 03  分管领导
         * 04  经办人
         */
        //主要领导分管领导看本单位的，，经办人只看自己
        filter.setCreateUser(userDto.getUserId());
        filter.setCrucialUser(userDto.getUserId());
        filter.setDeptId(userDto.getDeptId());
        filter.setInspectionId(userDto.getDeptId());
        if(ObjectUtils.isBlank(filter.getPaging()))
        {

            Paging paging = new Paging();
            paging.setPageSize(10);
            paging.setCurrentPage(1);
            filter.setPaging(paging);
        }
      //  List<TaskMain> taskMains = taskMainService.queryFilter(filter);
        List<TaskMainFilter> mainTask = appTaskService.getMainTask(filter);
        for (TaskMainFilter taskMainFilter : mainTask) {
            String categoryId = taskMainFilter.getCategoryId();
            String cateName = changeCateVale(categoryId);
            taskMainFilter.setCategoryName(cateName);
            String mainName = taskMainFilter.getMainName();
            String content = taskMainFilter.getContent();
           taskMainFilter.setMainName(StringUtils.isNotBlank(mainName)?StringEscapeUtils.unescapeHtml(mainName):"");
           taskMainFilter.setContent(StringUtils.isNotBlank(content)?StringEscapeUtils.unescapeHtml(content):"");

        }


        return coverMessage("200","返回成功",mainTask);
    }


    /**
     * 获取子任务
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/subtasklist",method = RequestMethod.POST)
    public Message getSubTaskList(@RequestBody TaskUnitFilter filter)
    {
        String loginerId = filter.getLoginerId();
        if(ObjectUtils.isBlank(loginerId))
        {
            return coverMessage("500","登陆超时，重新登录");

        }

        String taskMainId = filter.getTaskMainId();

        List<TaskUnit> subTaskList = appTaskService.getSubTaskList(filter);
        for (TaskUnit taskUnit : subTaskList) {
            String taskSubName = taskUnit.getTaskSubName();
            String taskMainName = taskUnit.getTaskMainName();
            taskUnit.setTaskMainName(StringEscapeUtils.unescapeHtml(taskMainName));
            taskUnit.setTaskSubName(StringEscapeUtils.unescapeHtml(taskSubName));
        }



        return coverMessage("200","返回子任务",subTaskList);
    }


    /**
     * 作战室获取攻坚总任务
     */
    @ResponseBody
    @RequestMapping(value = "/gjtasklist",method = RequestMethod.POST)
    public Message getgongjianTaskList(@RequestBody TaskMainFilter filter)
    {


        List<TaskMainFilter> gongJianTasks = taskMainService.getGongJianTasks(filter);

        return  coverMessage("200","攻坚总任务获取成功",gongJianTasks);
    }

    /**
     * 获取攻坚主任务
     */
    @ResponseBody
    @RequestMapping(value = "/gjmaintasklist",method = RequestMethod.POST)
    public Message gongjianMainTask(@RequestBody TaskMainFilter filter)
    {
        String gjId = filter.getGjId();
        if(StringUtils.isBlank(gjId))
        {
            return  coverMessage("200","gjId不能为空");
        }
        List<TaskMain> taskMains = taskMainService.queryFilter(filter);
        List<TaskMainFilter> datalist = new ArrayList<>();

        for (TaskMain taskMain : taskMains) {
            TaskMainFilter data = new TaskMainFilter();
            BeanUtils.copyProperties(taskMain,data);
            String inspectionId = taskMain.getInspectionId();
            if(StringUtils.isNotBlank(inspectionId))
            {
                String strDept = redisService.get("dept:" + inspectionId);
                try {
                    SysDept sysDept = JSONObject.parseObject(strDept, SysDept.class);
                    data.setInspectionName(sysDept.getDeptName());
                } catch (Exception e) {
                    data.setInspectionName("");
                }
            }
            data.setMainName(StringEscapeUtils.unescapeHtml(taskMain.getMainName()) );
            datalist.add(data);
        }
        //

//        List<TaskMain> gongJianTasks = taskMainService.getGongJianTasks(filter);

        return  coverMessage("200","攻坚主任务获取成功",datalist);
    }




}
